package edu.umn.contactviewer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import edu.umn.contactviewer.datastore.ContactListDataService;
import edu.umn.contactviewer.datastore.ContactListDataService.RequestResult;
import edu.umn.contactviewer.datastore.UpdateContactRequestResponseListener;
import edu.umn.contactviewer.datastore.impl.ContactListDataServiceRESTWebServiceImpl;

public class EditActivity extends Activity {

	private static final int FOREGROUND_COLOR = -16777216;
	private int MINIMUM_NAME_LENGTH;

	private final ContactListDataService contactListDataStore;
	private EditText nameTextView = null;
	private EditText titleTextView = null;
	private EditText phoneTextView = null;
	private EditText emailTextView = null;
	private EditText twitterIdTextView = null;
	private Contact contactToUpdate = null;

	public EditActivity() {
		contactListDataStore = new ContactListDataServiceRESTWebServiceImpl(this);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit);
		new EditToolbar();

		//init constant from resource file
		MINIMUM_NAME_LENGTH = getResources().getInteger(
				R.integer.minimum_name_length);

		// retrieve the contact to display from the intent extras
		contactToUpdate = (Contact) getIntent().getExtras()
				.get("contactToEdit");

		// initialize view members
		initializeViewMembers();

		// display the contact in the view
		initializeDisplayedContactInfo();
	}

	private void initializeViewMembers() {
		// cache view members
		nameTextView = (EditText) findViewById(R.id.edit_name);
		titleTextView = (EditText) findViewById(R.id.edit_title);
		phoneTextView = (EditText) findViewById(R.id.edit_phone);
		emailTextView = (EditText) findViewById(R.id.edit_email);
		twitterIdTextView = (EditText) findViewById(R.id.edit_twitterid);

		// attach text change listener to the name field to enable validation
		nameTextView.addTextChangedListener(new TextWatcher() {

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// empty implementation
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// empty implementation
			}

			public void afterTextChanged(Editable s) {
				validateNameTextField();
			}
		});
	}

	private void initializeDisplayedContactInfo() {
		// set text field data and set selection length
		nameTextView.setText(contactToUpdate.getName());
		nameTextView.setSelection(nameTextView.length());

		titleTextView.setText(contactToUpdate.getTitle());
		titleTextView.setSelection(titleTextView.length());

		phoneTextView.setText(contactToUpdate.getPhone());
		phoneTextView.setSelection(phoneTextView.length());

		emailTextView.setText(contactToUpdate.getEmail());
		emailTextView.setSelection(emailTextView.length());

		twitterIdTextView.setText(contactToUpdate.getTwitterId());
		twitterIdTextView.setSelection(twitterIdTextView.length());
	}

	private void updateDisplayedContactInfo() {
		// retrieve the text from the displayed fields
		contactToUpdate.setName(nameTextView.getText().toString());
		contactToUpdate.setTitle(titleTextView.getText().toString());
		contactToUpdate.setPhone(phoneTextView.getText().toString());
		contactToUpdate.setEmail(emailTextView.getText().toString());
		contactToUpdate.setTwitterId(twitterIdTextView.getText().toString());
	}

	private boolean validateNameTextField() {
		// name field is valid
		boolean isNameTextFieldIsValid = (nameTextView.getText().toString()
				.length() >= MINIMUM_NAME_LENGTH);
		if (!isNameTextFieldIsValid) {
			String errorString = getString(R.string.name_validation_error_string);
			ForegroundColorSpan fSpan = new ForegroundColorSpan(
					FOREGROUND_COLOR);
			SpannableStringBuilder ssBuilder = new SpannableStringBuilder(
					errorString);
			ssBuilder.setSpan(fSpan, 0, errorString.length(), 0);
			nameTextView.setError(ssBuilder);
		}

		return isNameTextFieldIsValid;
	}

	private boolean updatedFieldsValid() {
		return validateNameTextField();
	}

	private class EditToolbar extends ToolbarConfig {
		public EditToolbar() {
			super(EditActivity.this, getString(R.string.edit));
			Button rightButton = getToolbarRightButton();
			rightButton.setText(getString(R.string.save));
			rightButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {

					if (updatedFieldsValid()) {
						
						// Update the contact member with the udpated info. 
						updateDisplayedContactInfo();

						// Make asynchronous update request
						contactListDataStore.updateContact(
							contactToUpdate,
							new UpdateContactRequestResponseListener() {
								public void onUpdateContactResponse(RequestResult result, Contact contactToUpdate) {
									if (result == RequestResult.SUCCESS) {
										Toast.makeText(
											getApplicationContext(),
											getString(R.string.update_success_message),
											5).show();
										setResult(RESULT_OK);
										Intent intent = new Intent();
										intent.putExtra("contactForDetailsResults", contactToUpdate);
										setResult(RESULT_OK, intent);
										finishActivity();
									}
									else {
										Log.e(EditActivity.class.getSimpleName(),
											  "Error updating contact: " + contactToUpdate.getName());
										Toast.makeText(
											getApplicationContext(),
											getString(R.string.update_error_message),
											5).show();
									}
								}
							});
					} // end if updated fields are valid
				} // end Save button onClick
			}); // end Save button setOnClickListener
			
			rightButton.setVisibility(View.VISIBLE);
		}
	}
}
